package com.fl.nj.service.impl;

import com.fl.nj.entity.Menu;
import com.fl.nj.mapper.MenuMapper;
import com.fl.nj.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 菜单Service实现类
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findAll() {
        return menuMapper.findAll();
    }

    @Override
    public Menu findById(Long id) {
        return menuMapper.findById(id);
    }

    @Override
    public List<Menu> findByParentId(Long parentId) {
        return menuMapper.findByParentId(parentId);
    }

    @Override
    public int insert(Menu menu) {
        Date now = new Date();
        menu.setCreateTime(now);
        menu.setUpdateTime(now);
        return menuMapper.insert(menu);
    }

    @Override
    public int update(Menu menu) {
        menu.setUpdateTime(new Date());
        return menuMapper.update(menu);
    }

    @Override
    public int delete(Long id) {
        // 先检查是否有子菜单
        List<Menu> subMenus = findByParentId(id);
        if (subMenus != null && !subMenus.isEmpty()) {
            // 有子菜单，先删除子菜单
            for (Menu subMenu : subMenus) {
                delete(subMenu.getId());
            }
        }
        return menuMapper.delete(id);
    }

    @Override
    public List<Menu> findMenuTree() {
        return menuMapper.findMenuTree();
    }
}